package com.opengate.demo.api.biz.test.controller;

import com.opengate.base.currentuser.annotation.CurrentUser;
import com.opengate.base.currentuser.model.CurrentUserDto;
import com.opengate.base.result.Result;
import com.opengate.demo.api.biz.test.service.UserService;
import com.opengate.demo.contact.req.GetDemoInfoReq;
import com.opengate.demo.contact.resp.GetDemoInfoResp;
import com.opengate.demo.contact.resp.UserLoginResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import javax.validation.Valid;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description Demo接口
 * @date 2023/4/27 5:46 PM
 */
@Slf4j
@RestController
@RequestMapping("/demo")
@Api(tags = "Demo接口")
public class UserController {

    /** 注入service */
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/user/login")
    @ApiOperation(value = "登录", notes = "登录")
    public Result<UserLoginResp> userLogin(@Valid @RequestBody GetDemoInfoReq req) {
        return Result.success(userService.userLogin(req));
    }

    @PostMapping("/getDemoInfo")
    @ApiOperation(value = "查询", notes = "查询")
    public Result<GetDemoInfoResp> getDemoInfo(@Valid @RequestBody GetDemoInfoReq req) {
        return Result.success(userService.getDemoInfo(req));
    }

    @GetMapping("/test")
    @ApiOperation(value = "测试", notes = "测试")
    public Result<String> test(@CurrentUser CurrentUserDto currentUser) {
        return Result.success(userService.test(currentUser));
    }

    @GetMapping("/test/deferred")
    @ApiOperation(value = "测试deferred", notes = "测试，异步线程处理")
    public DeferredResult<Result<String>> testDeferred() {

        // 设置超时时间
        DeferredResult<Result<String>> deferredResult = new DeferredResult<>(1000L);

        // 设置超时回调
        deferredResult.onTimeout(
                () -> {
                    deferredResult.setResult(Result.fail("超时了"));
                });

        // 设置完成回调
        deferredResult.onCompletion(
                () -> {
                    log.info("调用完成");
                });
        deferredResult.setResult(Result.success(userService.testDeferred()));

        return deferredResult;
    }
}
